<?php

namespace frontend\modules\content\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use common\models\User;
use frontend\modules\content\models\Content;
use frontend\modules\content\models\searchs\Content as ContentSearch;

/**
 * Default controller for the `content` module
 */
class DefaultController extends Controller
{
    /**
     * Renders the index view for the module
     * @param int $cid
     * @return string
     */
    public function actionIndex($cid = null)
    {
        $searchModel = new ContentSearch();
        //$searchModel->catid = $cid;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $view = 'index';

        if (!is_null($searchModel->menu)){
            $menuParams = json_decode($searchModel->menu->params, true);
            if (isset($menuParams['template']) && !empty($menuParams['template'])){
                $view = $menuParams['template'];
            }
        }

        return $this->render($view,[
            'searchModel' => $searchModel,
            'list' => $dataProvider->getModels(),
            'mid' => Yii::$app->request->get('mid')
        ]);
    }

    /**
     * Displays a single Content model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        return $this->render('view', [
            'model' => $model,
            'user' => User::findOne($model->created_by)
        ]);
    }

    /**
     * Finds the Content model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Content the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Content::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('mod_content', 'The requested page does not exist.'));
    }
}
